import axios, { AxiosResponse, AxiosError } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import router from '@renderer/router'
import { refreshToken as refreshTokenAPI } from '@renderer/api/login'

// 创建axios实例
const request = axios.create({
  baseURL: (import.meta.env.VITE_API_BASE_URL as string) || 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求队列
let requestQueue: Array<() => void> = []
let isRefreshing = false

// 获取Token
const getToken = (): string | null => {
  return localStorage.getItem('accessToken')
}

// 获取RefreshToken
const getRefreshToken = (): string | null => {
  return localStorage.getItem('refreshToken')
}

// 保存Token
const saveTokens = (accessToken: string, refreshToken?: string) => {
  localStorage.setItem('accessToken', accessToken)
  if (refreshToken) {
    localStorage.setItem('refreshToken', refreshToken)
  }
}

// 清除Token
const clearTokens = () => {
  localStorage.removeItem('accessToken')
  localStorage.removeItem('refreshToken')
  localStorage.removeItem('userInfo')
}

// 跳转到登录页
const redirectToLogin = () => {
  clearTokens()
  if (router.currentRoute.value.path !== '/login') {
    router.push('/login')
    ElMessage.error('登录已过期，请重新登录')
  }
}

// Token刷新逻辑
const handleTokenRefresh = async (): Promise<string | null> => {
  if (isRefreshing) {
    // 如果正在刷新，将请求加入队列
    return new Promise((resolve) => {
      requestQueue.push(() => {
        resolve(getToken())
      })
    })
  }

  isRefreshing = true
  const refreshTokenValue = getRefreshToken()

  if (!refreshTokenValue) {
    isRefreshing = false
    redirectToLogin()
    return null
  }

  try {
    const response = await refreshTokenAPI({ refreshToken: refreshTokenValue })
    const { token, refreshToken: newRefreshToken, expiresIn } = response.data.data

    saveTokens(token, newRefreshToken)
    
    // 处理队列中的请求
    requestQueue.forEach((callback) => callback())
    requestQueue = []
    
    isRefreshing = false
    return token
  } catch (error) {
    console.error('Token刷新失败:', error)
    isRefreshing = false
    requestQueue = []
    redirectToLogin()
    return null
  }
}

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加JWT Token
    const token = getToken()
    if (token) {
      config.headers.Authorization = ` Bearer ${token}`
    }

    // 添加请求ID用于追踪
    config.headers['X-Request-ID'] = `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
    
    console.log(`API请求: ${config.method?.toUpperCase()} ${config.url}`, {
      params: config.params,
      data: config.data,
      headers: {
        'Authorization': config.headers.Authorization ? 'Bearer ***' : 'None',
        'X-Request-ID': config.headers['X-Request-ID']
      }
    })

    return config
  },
  (error) => {
    console.error('请求配置错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, config } = response
    
    console.log(`API响应: ${config.method?.toUpperCase()} ${config.url}`, {
      status: response.status,
      data: data
    })

    // 统一响应格式处理
    // 兼容两种响应格式：{code: 200} 和 {success: true}
    if (data.code === 200 || data.success === true) {
      return response
    } else {
      // 业务错误处理
      const errorMessage = data.message || '请求失败'
      console.error('业务错误:', errorMessage, data)
      
      ElMessage.error(errorMessage)
      return Promise.reject(new Error(errorMessage))
    }
  },
  async (error: AxiosError) => {
    const { config, response } = error
    
    console.error(`API错误: ${config?.method?.toUpperCase()} ${config?.url}`, {
      status: response?.status,
      statusText: response?.statusText,
      data: response?.data,
      message: error.message
    })

    // 处理不同的HTTP状态码
    if (response) {
      switch (response.status) {
        case 401:
          // Token过期或无效，尝试刷新Token
          if (!config?.url?.includes('/auth/refresh')) {
            const newToken = await handleTokenRefresh()
            if (newToken && config) {
              // 重新发起原始请求
              config.headers.Authorization = `Bearer ${newToken}`
              return request(config)
            }
          } else {
            // 刷新Token也失败了
            redirectToLogin()
          }
          break
          
        case 403:
          ElMessage.error('权限不足，无法访问该资源')
          break
          
        case 404:
          ElMessage.error('请求的资源不存在')
          break
          
        case 422:
          // 表单验证错误
          const validationErrors = (response.data as any)?.errors
          if (validationErrors) {
            const errorMessages = Object.values(validationErrors).flat()
            ElMessage.error(errorMessages.join(', '))
          } else {
            ElMessage.error('请求参数验证失败')
          }
          break
          
        case 429:
          ElMessage.error('请求过于频繁，请稍后再试')
          break
          
        case 500:
          ElMessage.error('服务器内部错误，请联系管理员')
          break
          
        case 502:
        case 503:
        case 504:
          ElMessage.error('服务暂时不可用，请稍后重试')
          break
          
        default:
          ElMessage.error(`请求失败: ${response.status} ${response.statusText}`)
      }
    } else {
      // 网络错误处理
      if (error.message.includes('timeout')) {
        ElMessage.error('请求超时，请检查网络连接')
      } else if (error.message.includes('Network Error')) {
        ElMessage.error('网络连接失败，请检查网络设置')
      } else {
        ElMessage.error('网络异常，请稍后重试')
      }
    }

    return Promise.reject(error)
  }
)

export default request
